package com.gainloop;

import java.net.MalformedURLException;
import java.util.Date;

import org.alexd.jsonrpc.JSONRPCException;

import com.ocpsoft.pretty.time.*;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.gainloop.R;
import com.gainloop.Api.ApiResponseObject;
import com.gainloop.Api.Users;
import com.gainloop.Api.Entity.User;
import com.gainloop.Data.Registry;
import com.gainloop.Utils.Constants;
import com.gainloop.Utils.ImageThreadLoader;
import com.gainloop.Utils.Constants.ListType;
import com.gainloop.Utils.ImageThreadLoader.ImageLoadedListener;

public class Profile extends TabsActivityAbstract {
	TabHost mTabHost;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.profile);

		initHeader();
		headerTitle.setText(R.string.profile);
		
		final ImageView profile = (ImageView) findViewById(R.id.profileImg);
		TextView username = (TextView) findViewById(R.id.profileUsername),
		location = (TextView) findViewById(R.id.profileLocation),
		wishes = (TextView) findViewById(R.id.profileWishes),
		helps = (TextView) findViewById(R.id.profileHelps),
		joined = (TextView) findViewById(R.id.profileJoined),
		locationLabel= (TextView) findViewById(R.id.profileLocationLabel);
		
		ImageView facebookLink = (ImageView) findViewById(R.id.profileFbBtn);
		Long userId = null;
		User user=null;
		//checking if a certain user was requested
		if (getIntent().hasExtra(Constants.userParam)){
			userId=(Long)getIntent().getExtras().get(Constants.userParam);
			ApiResponseObject<User> resp=null;
			Users users=new Users();
			try {
				resp=users.getById(userId);
			} catch (JSONRPCException e) {
				e.printStackTrace();
				throw new RuntimeException();
			}
			if (resp.getReturnCode()==0){
				user=resp.getData();
			}
			else{
				throw new RuntimeException(""+R.string.server_error+resp.getReturnCode());
			}
			
		}
		//no specific user was requested, getting active user.
		if (user==null){
			user=Registry.GetUser();
		}
		Log.v("Profile","User id: "+user.getId());
		try {
//			URL newurl = new URL(
//					"http://graph.facebook.com/"+user.getFbId()+"/picture?type=normal");
//			Bitmap bitmap = BitmapFactory.decodeStream(newurl
//					.openConnection().getInputStream());
//			
//			float dstWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
//			float dstHeight = (dstWidth / bitmap.getWidth()) * bitmap.getHeight();
//			
//			bitmap = Bitmap.createScaledBitmap(bitmap, (int) dstWidth, (int) dstHeight, true);
//			profile.setImageBitmap(bitmap);
			
			Bitmap cachedImage = ImageThreadLoader.GetInstance().loadImage("http://graph.facebook.com/"+user.getFbId()+"/picture?type=normal", 
					new ImageLoadedListener() {
				public void imageLoaded(Bitmap imageBitmap) {
					profile.setImageBitmap(getScaledBitmap(imageBitmap));          
				}
			});
			if(cachedImage != null)
				profile.setImageBitmap(getScaledBitmap(cachedImage));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		final Long userFbId = user.getFbId();
		facebookLink.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com/profile.php?id="+userFbId));
		        startActivity(i);	
			}
		});
		
		username.setTypeface(fontNormal);
		username.setText(user.getName());
		if (user.getLocationName()==null){
			locationLabel.setVisibility(View.INVISIBLE);
		}
		else{
			location.setText(user.getLocationName());
		}
		wishes.setText(user.getResolvedNum()+"/"+user.getWishesNum());
		helps.setText(""+user.getHelpsNum());
		PrettyTime p=new PrettyTime();
		if (user.getCreateTime().after(new Date(0))){
			joined.setText(p.format(user.getCreateTime()));
		}
		else{
			joined.setText("unknown");
		}
		mTabHost = (TabHost) findViewById(R.id.profileTabhost);
		mTabHost.setup(this.getLocalActivityManager());
		
		
		Log.v("user.getId=",Long.toString(user.getId()));
		
		mTabHost.addTab(mTabHost
				.newTabSpec("wishes")
				.setIndicator(
						createTabView(mTabHost.getContext(),
								R.string.wishes))
				.setContent(new Intent().setClass(this, WishList.class)
				.putExtra(Constants.listTypeParam,ListType.USER)
				.putExtra(Constants.userParam, user.getId())));
		
		
		mTabHost.addTab(mTabHost
				.newTabSpec("helps")
				.setIndicator(
						createTabView(mTabHost.getContext(),
								R.string.helps))
				.setContent(new Intent().setClass(this, HelpsList.class)
				.putExtra(Constants.listTypeParam,ListType.USER)
				.putExtra(Constants.userParam, user.getId())));

		mTabHost.addTab(mTabHost
				.newTabSpec("loops")
				.setIndicator(
						createTabView(mTabHost.getContext(),
								R.string.loops))
				.setContent(new Intent().setClass(this, LoopPage.class)
				));
	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);

		// TODO load activity only once
		MenuItem mi_home = menu.findItem(R.id.menuHome);
		mi_home.setIntent(new Intent(this, Home.class));
		
		MenuItem mi_newWish = menu.findItem(R.id.menuNewWish);
		mi_newWish.setIntent(new Intent(this, AddWish.class));
		
		MenuItem mi_search_gain = menu.findItem(R.id.menuSearch); 
		mi_search_gain.setIntent(new Intent(this, GainSearch.class));
		
		MenuItem mi_people = menu.findItem(R.id.menuPeople); 
		mi_people.setIntent(new Intent(this, People.class));
		
		menu.removeItem(R.id.menuProfile);
		return true;
	}
	
	Bitmap getScaledBitmap(Bitmap origin)
	{
		float dstWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics());
		float dstHeight = (dstWidth / origin.getWidth()) * origin.getHeight();

		return Bitmap.createScaledBitmap(origin, (int) dstWidth, (int) dstHeight, true);
	}
}